#!/usr/bin/python

import mechanize
import cookielib
import re,time,os

username = 'vamsee.reddy'
password = '17207734Uy'
term = "2117"
subject = "BIOL"
number = "241"
expect = 2


br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
br.set_handle_equiv(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
r = br.open('https://cas.ucalgary.ca/cas/?service=https://my.ucalgary.ca/uPortal2/Authentication')
br.select_form(nr=0)
br.form['username']=username
br.form['password']=password
br.submit()
# Looking at some results in link format
for l in br.links(url_regex=username):
	login = l
	break
br.open(login.url)

r = br.open('https://my.ucalgary.ca/uPortal2/SSOChannelAutoLogon?returnUrl=https://prdrps2.ehs.ucalgary.ca/psauthent')

# FUUUUCK YEAAA, IM IN!
# Now I can do whatever I want, ugh. Fuck you U of C.

status = re.compile("class='PSEDITBOXLABEL' >Status")

# Open class search
while 1:
	br.open('https://prdrps2.ehs.ucalgary.ca/psc/saprd/EMPLOYEE/HRMS/c/SA_LEARNER_SERVICES.CLASS_SEARCH.GBL?PORTALPARAM_PTCNAV=HC_CLASS_SEARCH&EOPP.SCNode=HRMS&EOPP.SCPortal=EMPLOYEE&EOPP.SCName=HCCC_SS_CATALOG&EOPP.SCLabel=Class%20Search%20%2f%20Browse%20Catalog&EOPP.SCPTfname=HCCC_SS_CATALOG&FolderPath=PORTAL_ROOT_OBJECT.CO_EMPLOYEE_SELF_SERVICE.HCCC_SS_CATALOG.HC_CLASS_SEARCH&IsFolder=false&PortalActualURL=https%3a%2f%2fprdrps2.ehs.ucalgary.ca%2fpsc%2fsaprd%2fEMPLOYEE%2fHRMS%2fc%2fSA_LEARNER_SERVICES.CLASS_SEARCH.GBL&PortalContentURL=https%3a%2f%2fprdrps2.ehs.ucalgary.ca%2fpsc%2fsaprd%2fEMPLOYEE%2fHRMS%2fc%2fSA_LEARNER_SERVICES.CLASS_SEARCH.GBL&PortalContentProvider=HRMS&PortalCRefLabel=Class%20Search&PortalRegistryName=EMPLOYEE&PortalServletURI=https%3a%2f%2fprdrps2.ehs.ucalgary.ca%2fpsp%2fsaprd%2f&PortalURI=https%3a%2f%2fprdrps2.ehs.ucalgary.ca%2fpsc%2fsaprd%2f&PortalHostNode=HRMS&NoCrumbs=yes')
	br.select_form(nr=0)
	br.form.set_all_readonly(False)
	br.form['CLASS_SRCH_WRK2_STRM$49$'] =[term]
	br.form['CLASS_SRCH_WRK2_SUBJECT$62$']=[subject]
	br.form['CLASS_SRCH_WRK2_CATALOG_NBR$70$']=number
	#br.form['ICStateNum']='4'
	br.form['ICAction']='CLASS_SRCH_WRK2_SSR_PB_CLASS_SRCH'
	r=br.submit()
	classes = len(status.findall(r.read()))
	if int(classes) != expect:
		os.system('sh ./notify.sh')
		quit()
	print "There are %i %s %i classes available" %(int(classes), str(subject),int(number))
	print "...please wait\n"
	time.sleep(15)